import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom"

import { Button, Col, message, Row } from "antd";
import { ArrowLeftOutlined, FullscreenOutlined, FullscreenExitOutlined, LineOutlined, CloseOutlined } from "@ant-design/icons";
import { NavComponent } from "./navComponent.jsx";
import { Modal, Navigator, Folder, FolderExplorContainer } from "./styled.jsx";
import TextArea from "./textarea";

import { BLOG_ICON_TYPE, FOLDER_ICON_TYPE } from "@/contains/iconTypeEnum.js";

import "./modalApp.css";
import dataManager from "@/utils/dataManager";
import indexedDBManager from "@/utils/indexedDB";

const Explorer = ({ state, dispatch }) => {
  const { selectFid, explorerTitleName, filePathData, folderList, isRenameId, 
    explorRequesId, barIconData, iframeZindex} = state;
  const navigate = useNavigate()
  
  const folderNode = useRef(null);
  const [useDom, setUseDom] = useState([]); // 使用的文件夹元素
  const [hoverId, setHoverId] = useState(-1); // 悬浮的id
  const [isShiftKey, setIsShiftKey] = useState(false); // 使用是否是左键
  const [isMax, setIsMax] = useState(false);

  // 获取文件夹数据
  useEffect(() => {
    getData();
  }, [explorRequesId]);
  // 初始化
  useEffect(() => {
    document.onkeydown = keyDownHandler;
    document.onkeyup = keyUpHandler;
    return () => {
      document.onkeydown = null;
      document.onkeyup = null;
    };
  }, []);
  // 鼠标按压事件
  const keyDownHandler = (e) => {
    if (e.key === "Shift") {
      setIsShiftKey(true);
    }
  };
  // 鼠标弹起事件
  const keyUpHandler = (e) => {
    setIsShiftKey(false);
  };
  // 文件夹点击事件
  const folderHandler = (e, id) => {
    e.preventDefault();
    e.stopPropagation();
    if (!isShiftKey) {
      setUseDom([id]);
    } else {
      if (!useDom.includes(id)) setUseDom(useDom.concat([id]));
      else {
        const data = useDom.slice();
        const index = useDom.indexOf(id);
        data.splice(index, 1);
        setUseDom(data);
      }
    }
  };
  // 本行开始设置鼠标移入事件
  function mouseOverHandler(e, id) {
    setHoverId(id);
  }
  function mouseOutHandler() {
    setHoverId(-1);
  }
  const mouseDownListener = () => {
    iframeZindex.forEach((item, index, arr) => {
      arr[index] = 20;
    });

    dispatch({
      type: "setState",
      payload: {
        isRenameId: [],
        iframeZindex,
        explorZIndex: 21,
      },
    });
  };
  const getData = async () => {
    try {
      const currentUser = await dataManager.getCurrentUser();
      if (!currentUser) return;

      const folders = await indexedDBManager.getFoldersByParent(selectFid, currentUser.uid);
      const files = await indexedDBManager.getFilesByFolder(selectFid, currentUser.uid);

      dispatch({
        type: "setState",
        payload: {
          folderList: [...folders, ...files],
        },
      });
    } catch (error) {
      console.error('获取文件夹数据失败:', error);
      dispatch({
        type: "setState",
        payload: {
          folderList: [],
        },
      });
    }
  };

  useEffect(() => {
    getData();
  }, [selectFid]);

  const openChildrenFolder = async (type, item, id, name) => {
    try {
      const currentUser = await dataManager.getCurrentUser();
      if (!currentUser) return;

      switch (type) {
        case FOLDER_ICON_TYPE:
          dispatch({
            type: "setState",
            payload: {
              selectFid: id,
              explorerTitleName: name,
              filePathData: filePathData.concat(item),
            },
          });
          break;
        case BLOG_ICON_TYPE:
          navigate("/blog", { state: { fid: id, uid: currentUser.uid, name } });
          break;
        default:
          break;
      }
    } catch (error) {
      console.error('打开文件夹失败:', error);
    }
  };
  const backOffPath = () => {
    if (filePathData.length === 1) {
      message.warn("已经到到达顶部了！");
      return;
    }
    filePathData.pop();
    dispatch({
      type: "setState",
      payload: {
        filePathData,
        selectFid: filePathData[filePathData.length - 1].fid,
        explorerTitleName: filePathData[filePathData.length - 1].name,
      },
    });
  };
  const handleExpand = () => {
    folderNode.current.style.width = "100%";
    folderNode.current.style.height = "100%";
    setNowX(0);
    setNowY(0);
    setIsMax(true);
  };

  const handleExitOutExpand = () => {
    setIsMax(false);
    folderNode.current.style.width = "80%";
    folderNode.current.style.height = "60%";
  };

  const closeOutHandlerClick = () => {
    const index = barIconData.findIndex((item) => item.iconType === 0);
    if (index !== -1) {
      barIconData.splice(index, 1);
    }
    // 关闭窗口
    dispatch({
      type: "setState",
      payload: {
        isFolderVisiable: false,
        barIconData,
      },
    });
  };
  const handleLineOut = () => {
    // 关闭窗口
    dispatch({
      type: "setState",
      payload: {
        isFolderVisiable: false,
        barIconData,
      },
    });
  };
  const handleContextMenu = (e) => {
    console.log(e);
    e.preventDefault();
    e.stopPropagation();
    dispatch({
      type: "setState",
      payload: {
        deskMenuVisible: true,
        deskMenuX: e.clientX,
        deskMenuY: e.clientY,
        menuType: "explor",
      },
    });
  };

  const handleFolderMenu = (e, item, fid) => {
    e.preventDefault();
    e.stopPropagation();
    dispatch({
      type: "setState",
      payload: {
        deskMenuVisible: false,
        folderMenuVisible: true,
        barMenuVisable: false,
        folderMenuX: e.clientX,
        folderMenuY: e.clientY,
        folderMenuSelectNum: fid,
        contextMeunPathData: filePathData.concat(item),
      },
    });
  };

  const [diffX, setdiffX] = useState(0);
  const [diffY, setdiffY] = useState(0);
  const [nowX, setNowX] = useState(0);
  const [nowY, setNowY] = useState(0);
  const [leftDown, setLeftDown] = useState(false);

  const mouseMoveListener = (e) => {
    const { clientX, clientY } = e;
    setNowX(clientX - diffX);
    setNowY(clientY - diffY);
  };

  const mouseDownHeaderListener = (e) => {
    const { clientX, clientY } = e;
    const { offsetLeft, offsetTop } = folderNode.current;
    setdiffX(clientX - offsetLeft);
    setdiffY(clientY - offsetTop);
    setLeftDown(true);
  };

  useEffect(() => {
    if (leftDown) {
      document.onmousemove = mouseMoveListener;
      document.onmouseup = mouseUpListener;
    } else {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }, [leftDown]);

  const mouseUpListener = (e) => {
    setdiffX(0);
    setdiffY(0);
    setLeftDown(false);
  };

  return (
    <FolderExplorContainer
      ref={folderNode}
      onContextMenu={handleContextMenu}
      onClick={mouseDownListener}
      x={nowX}
      y={nowY}
    >
      <Modal
        style={{
          height: "auto",
        }}
      >
        <div className="header" onMouseDown={mouseDownHeaderListener}>
          <Button
            style={{
              visibility: "inherit",
            }}
            icon={<ArrowLeftOutlined />}
            type="text"
            onClick={backOffPath}
          ></Button>
          <div className="title">{explorerTitleName}</div>

          <Button
            icon={<LineOutlined />}
            onClick={handleLineOut}
            type="text"
          ></Button>

          {!isMax && (
            <Button
              icon={<FullscreenOutlined />}
              onClick={handleExpand}
              type="text"
            ></Button>
          )}

          {isMax && (
            <Button
              icon={<FullscreenExitOutlined />}
              onClick={handleExitOutExpand}
              type="text"
            ></Button>
          )}

          <Button
            onClick={closeOutHandlerClick}
            icon={<CloseOutlined />}
            type="text"
          ></Button>
        </div>

        <Navigator>
          {filePathData?.map((item, index, arr) => (
            <NavComponent
              dispatch={dispatch}
              filePathData={arr}
              folder={item}
              key={item.fid}
            ></NavComponent>
          ))}
        </Navigator>

        <Row style={{ marginTop: "15px", justifyContent: "start" }}>
          {folderList.map((item, index) => (
            <Col span={3} key={index}>
              <Folder
                isFocus={useDom.includes(item.fid) || hoverId === item.fid}
                onClick={(e) => folderHandler(e, item.fid)}
                onContextMenu={(e) => handleFolderMenu(e, item, item.fid)}
                onMouseOver={(e) => {
                  mouseOverHandler(e, item.fid);
                }}
                onMouseOut={mouseOutHandler}
                onDoubleClick={() =>
                  openChildrenFolder(item.iconType, item, item.fid, item.name)
                }
              >
                <Folder.Img src={item.iconUrl} />
                {!isRenameId.includes(item.fid) && (
                  <Folder.Text>{item.name}</Folder.Text>
                )}
                {isRenameId.includes(item.fid) && (
                  <TextArea
                    state={state}
                    dispatch={dispatch}
                    name={item.name}
                    index={index}
                  />
                )}
              </Folder>
            </Col>
          ))}
        </Row>
      </Modal>
    </FolderExplorContainer>
  );
};

export default Explorer;
